<?php
class CategoryController extends Zend_Controller_Action {
	protected $_category;
	protected $_item;
	public function init()
	{
		$id = (int) $this->_getParam('id',0);
		$this->_item =  $this->_getParam('item',null);
		
		if($id>0){
			$this->_category =  Model_Category::create($id,$this->_item);
		} else {
			$this->_category =  Model_Category::create(null, $this->_item);
		}
	}
	
	public function viewAction()
	{

	}
	public function addAction()
	{
		$form = new Form_Category();
		$this->view->form = $form;
		if($this->getRequest()->isPost()){
			if($form->isValid($this->getRequest()->getPost())){
				$children = $this->_category->createChildren();
				$children->fill($form->getValues());
				$children->add();
				$this->_redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}
	public function editAction()
	{
		$this->view->headTitle()->append('Редактирование категории');
		$id = (int) $this->_getParam('id',0);
		$category = $this->_category;
		$form = new Form_Category($id, 'edit', $this->_item);
		$this->view->categorys = $category->getAll();
		$form->populate($category->populate());
		$this->view->parentCategory = $category->getRow(); 
		$this->view->form = $form;
		if($this->getRequest()->isPost()){
			if($form->isValid($this->getRequest()->getPost())){
				$category->fill($form->getValues());
				$category->save();
				$this->_redirect($this->_item);
			}
		}
	}
	
	public function deleteAction()
	{
		$category = $this->_category;
		$category->delete();
		$this->_redirect('/category/');
	}
	
	public function indexAction()
	{
		$id = (int) $this->_getParam('id' , 0);
		$this->view->id = $id;
		$currentCategory = $this->view->currentCategory = $this->_category->getRow();
		$this->view->parent = $this->_category->getParent();
	 	$this->view->places = $this->_category->getItems();
	}
}